<script setup lang="ts">
import { ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { updateRoleApi, getSuccessStatus } from '@/api/role'

const props = defineProps<{
	editRow: any
}>()

const formInstance = ref<FormInstance | null>(null)
const initState = {
	roleName: '',
	roleCode: '',
	description: '',
}
const state = ref<ObjType>(initState)

const formLayout = {
	style: 'margin: 0 10px',
	labelWidth: 'auto',
	labelPosition: 'left',
}

const rules = {
	roleName: [{ required: true, message: '请输入角色名！', trigger: 'change' }],
	roleCode: [{ required: true, message: '请输入角色名！', trigger: 'change' }],
	description: [{ required: true, message: '请输入角色名！', trigger: 'change' }],
}

function init() {
	formInstance.value?.resetFields()
	state.value = initState
	Object.keys(state.value).forEach((k) => {
		state.value[k] = props.editRow[k]
	})
}

async function formCommit() {
	try {
		await formInstance.value?.validate()
		const res = await updateRoleApi([{ ...props.editRow, ...state.value }])
		if (res.code) {
			if (res.code == getSuccessStatus()) {
				return true
			}
		}
	} catch (error) {
		console.log(error)
	}
}

defineExpose({
	init,
	formCommit,
})
</script>

<template>
	<el-form :model="state" :rules="rules" v-bind="formLayout" ref="formInstance">
		<el-row :gutter="24">
			<el-col :span="12">
				<el-form-item prop="roleName" label="角色名">
					<el-input v-model="state.roleName" placeholder="角色名称必须唯一" clearable />
				</el-form-item>
			</el-col>
			<el-col :span="12">
				<el-form-item prop="roleName" label="角色编码">
					<el-input v-model="state.roleCode" placeholder="角色编码必须唯一" clearable />
				</el-form-item>
			</el-col>
			<el-col :span="24">
				<el-form-item prop="roleName" label="角色描述">
					<el-input v-model="state.description" placeholder="角色描述" clearable />
				</el-form-item>
			</el-col>
		</el-row>
	</el-form>
</template>
